from dataclasses import dataclass, field
from types import MappingProxyType
from typing import Generic, TypeVar, Optional

T = TypeVar('T')

@dataclass
class Response(Generic[T],object):
    """
    通用返回结果类
    """
    code: int = field(default=0)
    msg: str = field(default="")
    data: Optional[T] = field(default=None)

    def __init__(self, code: int, msg: str, data: Optional[T] = None):
        self.code = code
        self.msg = msg
        self.data = data

    # def to_dict(self):
    #     return {
    #         "code": self.code,
    #         "msg": self.msg,
    #         "data": json.loads(json.dumps(self.data, default=lambda o: o.__dict__)) if self.data else None
    #     }

    import json
    from types import MappingProxyType

    def to_dict(self):
        """将 Response 对象转换为字典"""
        return {
            "code": self.code,
            "msg": self.msg,
            "data": self._serialize_data(self.data)
        }

    def _serialize_data(self, data):
        """递归转换数据，确保 data 可以是对象、数组、字典等"""
        if data is None:
            return None
        if isinstance(data, MappingProxyType):  # 处理 MappingProxyType
            data = dict(data)
        if isinstance(data, list):  # 处理数组
            return [self._serialize_data(item) for item in data]
        if isinstance(data, dict):  # 处理字典
            return {key: self._serialize_data(value) for key, value in data.items()}
        if hasattr(data, "to_dict"):  # 处理对象（有 to_dict 方法）
            return data.to_dict()
        if hasattr(data, "__dict__"):  # 处理普通类对象（没有 to_dict 方法）
            return {key: self._serialize_data(value) for key, value in vars(data).items()}
        return data  # 其他基础类型（int, str, bool, float）直接返回

    def success(self, code: int, message: str, data: Optional[T] = None) -> 'Response[T]':
        """
        成功
        """
        return Response(code=code, msg=message, data=data)

    @staticmethod
    def success_static(code: int, message: str) -> 'Response[None]':
        """
        成功2.0
        :param code: 状态码
        :param message: 信息
        """
        return Response(code=code, msg=message)

    @staticmethod
    def error(code: int, message: str) -> 'Response[None]':
        """
        错误信息
        :param code: 错误状态码
        :param message: 错误信息
        """
        return Response(code=code, msg=message, data=None)

